#!/usr/bin/env bash

set_ip() {
    if=$(ifconfig | grep -v '^lo' | grep -o '^[^[:blank:]]*:' | grep -o '[^:]*')
    mac=$(ifconfig | grep -A 2 "${if}:" | grep "ether" | grep -Eo '(\w{2}:){5}\w{2}')
    field1=$(echo $(( 0x$(echo $mac | grep -Eo '\w{2}:\w{2}$' | grep -Eo '^\w+{2}') )))
    field2=$(echo $(( 0x$(echo $mac | grep -Eo '\w{2}$') )))
    addr="10.10.${field1}.${field2}/8"

    ifconfig $if flush
    ifconfig $if inet $addr up
    route flush
    route add default 10.0.0.1
}

ssh_login() {
    user="root"
    # passwd -d $user
    sed -ri."" 's/^ *#* *(PermitEmptyPasswords).*/\1 yes/' /etc/ssh/sshd_config
    sed -ri."" 's/^ *#* *(PermitRootLogin).*/\1 yes/' /etc/ssh/sshd_config
    sed -ri."" 's/^ *#* *(UsePAM).*/\1 yes/' /etc/ssh/sshd_config
    sed -ri."" 's/^ *#* *(UseDNS).*/\1 no/' /etc/ssh/sshd_config

    service sshd restart
}

set_pub_key() {
    PUBKEY="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDk/CSaXip7wwa2xsDaZm6eKmyET91fI28ufdVMZvsym7s8y0QVxdO16t9IlbH9ognp/zLETJSl1MxoEz1R2I9rE+R0eraeBT/LIsF5nIyMBZ/Zk5SRNrociW+9w4AxWZHcugGznVFIxbeC2Ja/q4xxDWRbtPB5nv2R92eTwZZ6TovxjmSGXUcBVRVFgvE0k7KgdRCGK9q0JOUZMT2d3fs8FkOJPeSznnawaUiLlLYFsY1R4F/+0r+zlbDgKrBmnjv1GYKohBcFMsw10m08cU3UjJym67R0I2NKMAFhWBZAh4IGMIfg7w3Ua2K4nHQwlcnOWuZ7jzll/nYRmrS9T3LF root@718f9c9841a8"
    sshpath="/root/.ssh"
    mkdir -p $sshpath
    echo $PUBKEY > ${sshpath}/authorized_keys
    chmod -R 0600 $sshpath
}

start_ttrexec_daemon() {
    cmd_name="ttrexec-daemon"
    cmd_path="/usr/local/bin/${cmd_name}"
    $cmd_path -a 0.0.0.0 -p 22000 2>/tmp/${cmd_name}_stderr.log >/tmp/${cmd_name}_stdout.log &
}

set_ip
ssh_login
set_pub_key

start_ttrexec_daemon
